package com.osi.mes.qm.camera;
import java.awt.Canvas;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Properties;

import pnuts.lang.Context;

import com.datasweep.compatibility.ui.File;
import com.osi.mes.qm.base.constants.IBasicConstants;
import com.osi.mes.qm.services.QmChkTbService;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.WString;

public class CameraWindow extends QmChkTbService implements WindowListener, ItemListener, ActionListener {
	private int m_prevWnd, m_videoInput, m_deviceCount, m_deviceIndex,
			m_formatCount, m_formatIndex;
	private ArrayList<Integer> m_formatIndices;
	private Frame m_mainFrame;
	private Panel m_mainPanel;
	private Canvas m_prevCanvas;
	private Choice m_deviceChoice;
	private JRButton m_grabButton;
	private JRButton m_zoomInButton, m_zoomOutButton, m_zoomLeftButton,
			m_zoomUpButton, m_zoomRightButton, m_zoomDownButton;
	private JRButton m_rolButton, m_rorButton;
	
	private String fileName;
	private String FTPFolder;
	
	private String ftpcHome  = "";
	
	private boolean hasFile = false;
	
	public static void main(String[] args) throws Exception{
		new CameraWindow(null);
	}

	public CameraWindow(Context context) throws Exception{
		super(context);
		
		ftpcHome = "C:\\.FTPC\\" + getFunctions().getSiteId()+"\\TEMP";
		if(!File.isDirectory(ftpcHome) && !File.exists(ftpcHome))
		{
			ftpcHome = getDefaultDir();
		}
			
		final Dimension windowSize = new Dimension(600, 400);
		final String windowText =getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.BBQ_ASS_WIN_NAME);
		Dimension scrnSize = new Dimension();
		Point windowPoint = new Point();

		scrnSize = Toolkit.getDefaultToolkit().getScreenSize();
		windowPoint.x = (scrnSize.width - windowSize.width) / 2;
		windowPoint.y = (scrnSize.height - windowSize.height) / 2;

		m_mainFrame = new Frame(windowText);
		m_mainFrame.addWindowListener(this);
		m_mainFrame.setSize(windowSize);
		m_mainFrame.setLocation(windowPoint);
		m_mainFrame.setResizable(false);

		m_mainPanel = new Panel();
		m_mainPanel.setLayout(null);
		m_mainPanel.setVisible(true);

		m_prevCanvas = new Canvas();
		m_prevCanvas.setLocation(15, 15);
		m_prevCanvas.setSize(400, 300);
		m_prevCanvas.setBackground(Color.black);
		m_prevCanvas.setFocusable(true);
		m_prevCanvas.setVisible(true);
	    
		m_deviceChoice = new Choice();
		m_deviceChoice.setLocation(150, 350);
		m_deviceChoice.setSize(200, 21);
		m_deviceChoice.addItemListener(this);
		m_deviceChoice.setVisible(true);
		
//		Font f =  new Font("宋体",Font.PLAIN,12);
//		UIManager.put("Button.font",f);
		String btnText  = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_GRAB);
		m_grabButton = new JRButton(btnText);
//		m_grabButton.setFont(new Font("system", Font.PLAIN, 12));
		m_grabButton.setLocation(440, 286);
		m_grabButton.setSize(150, 21);
		m_grabButton.addActionListener(this);
		m_grabButton.setVisible(true);

		String inText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_IN);
		m_zoomInButton = new JRButton(inText);
		m_zoomInButton.setLocation(440, 15);
		m_zoomInButton.setSize(100, 21);
		m_zoomInButton.addActionListener(this);
		m_zoomInButton.setVisible(true);

		String zoomOutText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_OUT);
		m_zoomOutButton = new JRButton(zoomOutText);
		m_zoomOutButton.setLocation(440, 41);
		m_zoomOutButton.setSize(100, 21);
		m_zoomOutButton.addActionListener(this);
		m_zoomOutButton.setVisible(true);

		String zoomUpText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_UP);
		m_zoomUpButton = new JRButton(zoomUpText);
		m_zoomUpButton.setLocation(440, 82);
		m_zoomUpButton.setSize(100, 21);
		m_zoomUpButton.addActionListener(this);
		m_zoomUpButton.setVisible(true);

		String zoomDownText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_DOWN);
		m_zoomDownButton = new JRButton(zoomDownText);
		m_zoomDownButton.setLocation(440, 108);
		m_zoomDownButton.setSize(100, 21);
		m_zoomDownButton.addActionListener(this);
		m_zoomDownButton.setVisible(true);

		String zoomLeftText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_LEFT);
		m_zoomLeftButton = new JRButton(zoomLeftText);
		m_zoomLeftButton.setLocation(440, 134);
		m_zoomLeftButton.setSize(100, 21);
		m_zoomLeftButton.addActionListener(this);
		m_zoomLeftButton.setVisible(true);

		String zoomRight = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_RIGHT);
		m_zoomRightButton = new JRButton(zoomRight);
		m_zoomRightButton.setLocation(440, 160);
		m_zoomRightButton.setSize(100, 21);
		m_zoomRightButton.addActionListener(this);
		m_zoomRightButton.setVisible(true);

		String rolText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_ROL);
		m_rolButton = new JRButton(rolText);
		m_rolButton.setLocation(440, 201);
		m_rolButton.setSize(100, 21);
		m_rolButton.addActionListener(this);
		m_rolButton.setVisible(true);

		String rorText = getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_ROR);
		m_rorButton = new JRButton(rorText);
		m_rorButton.setLocation(440, 227);
		m_rorButton.setSize(100, 21);
		m_rorButton.addActionListener(this);
		m_rorButton.setVisible(true);

		m_mainPanel.add(m_prevCanvas);
//		m_mainPanel.add(m_deviceChoice);
		m_mainPanel.add(m_grabButton);
		m_mainPanel.add(m_zoomInButton);
		m_mainPanel.add(m_zoomOutButton);
		m_mainPanel.add(m_zoomUpButton);
		m_mainPanel.add(m_zoomDownButton);
		m_mainPanel.add(m_zoomLeftButton);
		m_mainPanel.add(m_zoomRightButton);
		m_mainPanel.add(m_rolButton);
		m_mainPanel.add(m_rorButton);
//		m_mainPanel.add(label);

		m_mainFrame.add(m_mainPanel);
		m_mainFrame.setVisible(true);
	}
	
	public void setFileInfo(String ftpFolder)
	{
		this.FTPFolder = ftpFolder;
	}
	
	public boolean hasUploadFile()
	{
		return hasFile;
	}
	
	 public static String getDefaultDir()
		{
			Properties properties = System.getProperties();
			String osName = properties.getProperty("os.name","unknown_os_name");
			if (osName != null && osName.startsWith("Windows"))
			{
				String appData = System.getenv("APPDATA");
				if (appData == null)
				{
					// Note that on different Windows OS, the path may be different.
					appData = System.getenv("ALLUSERSPROFILE")
						+ System.getProperty("file.separator")
						+ "Application Data";
				}
				return appData;
			}
			return System.getProperty("user.home");
		}

	protected boolean openDevice(int deviceIndex) {
		boolean ret;

		m_deviceIndex = deviceIndex;
		m_formatIndex = m_formatIndices.get(m_deviceIndex);
		m_deviceChoice.select(m_deviceIndex);

		ret = VideoInput.INSTANCE.OpenDevice(m_videoInput, m_deviceIndex);
		ret &= VideoInput.INSTANCE.SetDeviceFormatIndex(m_videoInput,
				m_deviceIndex, m_formatIndex);
		ret &= VideoInput.INSTANCE.StartPlayDevice(m_videoInput, m_deviceIndex);

		for (int i = 0; i < m_formatCount; i++) {
			Pointer dev = new Memory(2048);
			dev.clear(2048);
			VideoInput.INSTANCE.GetDeviceFormatName(m_videoInput,
					m_deviceIndex, i, dev, 1024);
		}

		return ret;
	}

	protected boolean closeDevice(int deviceIndex) {
		boolean ret;

		m_deviceIndex = -1;
		ret = VideoInput.INSTANCE.StopPlayDevice(m_videoInput, m_deviceIndex);
		ret &= VideoInput.INSTANCE.CloseDevice(m_videoInput, m_deviceIndex);

		return ret;
	}

	@Override
	public void windowClosing(WindowEvent e) {
		m_mainFrame.dispose();
	}

	@Override
	public void windowClosed(WindowEvent e) {
		for (int i = 0; i < m_deviceCount; i++) {
			closeDevice(i);
		}

		VideoInput.INSTANCE.SetPreviewWindow(m_videoInput, 0);
		VideoInput.INSTANCE.ReleaseVideoInput(m_videoInput);
	}

	@Override
	public void windowOpened(WindowEvent e) {
		final String deviceName = "[1a3c:";

		m_prevWnd = (int) Native.getComponentID(m_prevCanvas);
		m_videoInput = VideoInput.INSTANCE.CreateVideoInput();
		m_deviceCount = VideoInput.INSTANCE.GetDeviceCount(m_videoInput);
		m_deviceIndex = -1;
		m_formatCount = 0;
		m_formatIndex = 0;

		VideoInput.INSTANCE.SetPreviewWindow(m_videoInput, m_prevWnd);
		m_deviceChoice.removeAll();
		m_formatIndices = new ArrayList<Integer>();

		for (int i = 0; i < m_deviceCount; i++) {
			Pointer dev = new Memory(2048);
			String deviceName0;

			dev.clear(2048);
			VideoInput.INSTANCE.GetDeviceName(m_videoInput, i, dev, 1024);
			deviceName0 = dev.getString(0, true);
			m_deviceChoice.add(deviceName0);

			if (deviceName0.contains(deviceName)) {
				m_deviceIndex = i;
			}

			m_formatIndices.add(0);
		}

		if (m_deviceIndex >= 0) {
			openDevice(m_deviceIndex);
		}
		else
		{
			getFunctions().dialogError(getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_NO_EQU));
		}
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
	}

	@Override
	public void itemStateChanged(ItemEvent arg0) {
		Object source = arg0.getSource();

		if (source == m_deviceChoice) {
			openDevice(m_deviceChoice.getSelectedIndex());
		} 
	}
	
	private void grabPicToFTP() throws Exception
	{
		if (!ftpcHome.endsWith("\\")) {
			ftpcHome += "\\";
		}
		
		if (this.FTPFolder != null) {
			
			fileName = super.getSerialNum()+IBasicConstants.CAMERA_PIC_TYPE;
			WString wsz = new WString(ftpcHome + fileName);
			boolean isSucc = VideoInput.INSTANCE.GrabToFile(m_videoInput, wsz);
			if(isSucc)
			{
				isSucc = super.uploadRptToFtp(ftpcHome + fileName, FTPFolder);
				if(isSucc)
				{
					hasFile = true;
					getFunctions().dialogOk(getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_GRAB_PIC),
							getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_GRAB_PIC_SUCC)		
					);
					File.delete(ftpcHome + fileName);
					return ;
				}
				
			}
			if(File.exists(ftpcHome + fileName))
				File.delete(ftpcHome + fileName);
			getFunctions().dialogError(getFunctions().getMessage(IBasicConstants.SAMPLE_RESULT_MSG,IBasicConstants.CAMERA_GRAB_PIC_FAILED));
		}
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		Object source = arg0.getSource();

		if (source == m_grabButton) {
			 try {
				grabPicToFTP();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} 
		else if (source == m_zoomInButton) {
			VideoInput.INSTANCE.ZoomDeviceDstRect(m_videoInput, m_deviceIndex,
					0.95f, 0.95f);
		} else if (source == m_zoomOutButton) {
			VideoInput.INSTANCE.ZoomDeviceDstRect(m_videoInput, m_deviceIndex,
					1.05f, 1.05f);
		} else if (source == m_zoomUpButton) {
			VideoInput.INSTANCE.MoveDeviceDstRect(m_videoInput, m_deviceIndex,
					0, -0.05f);
		} else if (source == m_zoomDownButton) {
			VideoInput.INSTANCE.MoveDeviceDstRect(m_videoInput, m_deviceIndex,
					0, 0.05f);
		} else if (source == m_zoomLeftButton) {
			VideoInput.INSTANCE.MoveDeviceDstRect(m_videoInput, m_deviceIndex,
					-0.05f, 0);
		} else if (source == m_zoomRightButton) {
			VideoInput.INSTANCE.MoveDeviceDstRect(m_videoInput, m_deviceIndex,
					0.05f, 0);
		} else if (source == m_rolButton) {
			int angle = VideoInput.INSTANCE.GetDeviceRotate(m_videoInput,
					m_deviceIndex);
			if (angle < 90) angle += 360;
			angle -= 90;
			VideoInput.INSTANCE.SetDeviceRotate(m_videoInput, m_deviceIndex,
					angle);
		} else if (source == m_rorButton) {
			int angle = VideoInput.INSTANCE.GetDeviceRotate(m_videoInput,
					m_deviceIndex);
			if (angle > 270) angle -= 360;
			angle += 90;
			VideoInput.INSTANCE.SetDeviceRotate(m_videoInput, m_deviceIndex,
					angle);
		}
	}
}
